import { defineStore } from 'pinia'
import { DatabaseService } from '@/services/database'

export const useConnectionStore = defineStore('connection', {
  state: () => ({
    // 连接配置列表
    connections: [],
    
    // 连接状态映射 connectionId -> status
    connectionStatus: new Map(),
    
    // 当前激活的连接ID
    activeConnectionId: null,
    
    // 加载状态
    loading: false,
    
    // 错误信息
    errors: new Map()
  }),
  
  getters: {
    // 获取指定连接配置
    getConnection: (state) => (connectionId) => {
      return state.connections.find(conn => conn.id === connectionId)
    },
    
    // 获取连接状态
    getConnectionStatus: (state) => (connectionId) => {
      return state.connectionStatus.get(connectionId) || {
        isConnected: false,
        connecting: false,
        error: null,
        lastConnected: null,
        databases: []
      }
    },
    
    // 获取已连接的连接列表
    connectedConnections: (state) => {
      return state.connections.filter(conn => {
        const status = state.connectionStatus.get(conn.id)
        return status && status.isConnected
      })
    },
    
    // 获取当前激活的连接
    activeConnection: (state) => {
      if (!state.activeConnectionId) return null
      return state.connections.find(conn => conn.id === state.activeConnectionId)
    },
    
    // 按类型分组的连接
    connectionsByType: (state) => {
      const grouped = {}
      state.connections.forEach(conn => {
        if (!grouped[conn.type]) {
          grouped[conn.type] = []
        }
        grouped[conn.type].push(conn)
      })
      return grouped
    }
  },
  
  actions: {
    // 加载所有连接配置
    async loadConnections() {
      this.loading = true
      this.errors.clear()
      
      try {
        const configs = await DatabaseService.getAllConfigs()
        this.connections = configs || []
        
        // 初始化连接状态
        this.connections.forEach(conn => {
          if (!this.connectionStatus.has(conn.id)) {
            this.connectionStatus.set(conn.id, {
              isConnected: false,
              connecting: false,
              error: null,
              lastConnected: null,
              databases: []
            })
          }
        })
        
        return this.connections
      } catch (error) {
        this.errors.set('load', error.message)
        console.error('Failed to load connections:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 保存连接配置
    async saveConnection(config) {
      try {
        const savedConfig = await DatabaseService.saveConfig(config)
        
        // 添加到本地列表
        const existingIndex = this.connections.findIndex(conn => conn.id === savedConfig.id)
        if (existingIndex >= 0) {
          this.connections[existingIndex] = savedConfig
        } else {
          this.connections.push(savedConfig)
        }
        
        // 初始化连接状态
        this.connectionStatus.set(savedConfig.id, {
          isConnected: false,
          connecting: false,
          error: null,
          lastConnected: null,
          databases: []
        })
        
        return savedConfig
      } catch (error) {
        this.errors.set(`save:${config.id}`, error.message)
        throw error
      }
    },
    
    // 更新连接配置
    async updateConnection(config) {
      try {
        const updatedConfig = await DatabaseService.updateConfig(config)
        
        // 更新本地列表
        const index = this.connections.findIndex(conn => conn.id === config.id)
        if (index >= 0) {
          this.connections[index] = updatedConfig
        }
        
        return updatedConfig
      } catch (error) {
        this.errors.set(`update:${config.id}`, error.message)
        throw error
      }
    },
    
    // 获取单个连接配置
    async getConfig(configId) {
      try {
        const config = await DatabaseService.getConfig(configId)
        return config
      } catch (error) {
        this.errors.set(`getConfig:${configId}`, error.message)
        throw error
      }
    },
    
    // 删除连接配置
    async deleteConnection(connectionId) {
      try {
        // 先断开连接
        try {
          await this.disconnectFromDatabase(connectionId)
        } catch (disconnectError) {
          console.warn('断开连接失败，继续删除操作:', disconnectError.message)
        }
        
        // 删除配置（添加超时处理）
        const deletePromise = DatabaseService.deleteConfig(connectionId)
        
        // 创建超时Promise
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => {
            reject(new Error('删除连接超时，前端自动超时'))
          }, 8000) // 8秒超时
        })
        
        // 使用Promise.race实现超时控制
        await Promise.race([deletePromise, timeoutPromise])
        
        // 从本地列表移除
        const index = this.connections.findIndex(conn => conn.id === connectionId)
        if (index >= 0) {
          this.connections.splice(index, 1)
        }
        
        // 清除状态
        this.connectionStatus.delete(connectionId)
        this.errors.delete(`connect:${connectionId}`)
        
        // 如果是当前激活的连接，清除激活状态
        if (this.activeConnectionId === connectionId) {
          this.activeConnectionId = null
        }
        
      } catch (error) {
        // 即使出错，也尝试从本地移除
        const index = this.connections.findIndex(conn => conn.id === connectionId)
        if (index >= 0) {
          console.warn('删除出错，但仍从本地移除连接:', error.message)
          this.connections.splice(index, 1)
          this.connectionStatus.delete(connectionId)
          this.errors.delete(`connect:${connectionId}`)
          
          if (this.activeConnectionId === connectionId) {
            this.activeConnectionId = null
          }
        }
        
        this.errors.set(`delete:${connectionId}`, error.message)
        throw error
      }
    },
    
    // 连接到数据库
    async connectToDatabase(connectionId) {
      const connection = this.getConnection(connectionId)
      if (!connection) {
        throw new Error('连接配置不存在')
      }
      
      // 设置连接中状态
      this.setConnectionStatus(connectionId, {
        connecting: true,
        error: null
      })
      
      try {
        // 测试连接
        await DatabaseService.testConnection(connection)
        
        // 获取数据库列表
        const databases = await DatabaseService.listDatabases(connectionId)
        
        // 设置连接成功状态
        this.setConnectionStatus(connectionId, {
          isConnected: true,
          connecting: false,
          error: null,
          lastConnected: new Date(),
          databases: databases || []
        })
        
        // 设置为激活连接
        this.activeConnectionId = connectionId
        
        // 更新最后使用时间
        connection.lastUsed = new Date()
        
        return true
      } catch (error) {
        // 设置连接失败状态
        this.setConnectionStatus(connectionId, {
          isConnected: false,
          connecting: false,
          error: error.message,
          lastConnected: null,
          databases: []
        })
        
        this.errors.set(`connect:${connectionId}`, error.message)
        throw error
      }
    },
    
    // 断开数据库连接
    async disconnectFromDatabase(connectionId) {
      try {
        await DatabaseService.closeConnection(connectionId)
        
        // 设置断开连接状态
        this.setConnectionStatus(connectionId, {
          isConnected: false,
          connecting: false,
          error: null,
          databases: []
        })
        
        // 如果是当前激活的连接，清除激活状态
        if (this.activeConnectionId === connectionId) {
          this.activeConnectionId = null
        }
        
        this.errors.delete(`connect:${connectionId}`)
        
      } catch (error) {
        this.errors.set(`disconnect:${connectionId}`, error.message)
        throw error
      }
    },
    
    // 测试连接
    async testConnection(config) {
      try {
        await DatabaseService.testConnection(config)
        return true
      } catch (error) {
        throw error
      }
    },
    
    // 设置连接状态
    setConnectionStatus(connectionId, statusUpdate) {
      const currentStatus = this.connectionStatus.get(connectionId) || {
        isConnected: false,
        connecting: false,
        error: null,
        lastConnected: null,
        databases: []
      }
      
      this.connectionStatus.set(connectionId, {
        ...currentStatus,
        ...statusUpdate
      })
    },
    
    // 刷新连接状态
    async refreshConnectionStatus(connectionId) {
      try {
        const status = await DatabaseService.getConnectionStatus(connectionId)
        this.setConnectionStatus(connectionId, status)
        return status
      } catch (error) {
        this.setConnectionStatus(connectionId, {
          isConnected: false,
          connecting: false,
          error: error.message
        })
        throw error
      }
    },
    
    // 刷新所有连接状态
    async refreshAllConnectionStatus() {
      const promises = this.connections.map(conn => 
        this.refreshConnectionStatus(conn.id).catch(error => {
          console.warn(`Failed to refresh status for ${conn.name}:`, error)
        })
      )
      
      await Promise.allSettled(promises)
    },
    
    // 设置激活连接
    setActiveConnection(connectionId) {
      const connection = this.getConnection(connectionId)
      if (connection) {
        this.activeConnectionId = connectionId
      }
    },
    
    // 获取连接的数据库列表
    async getConnectionDatabases(connectionId, force = false) {
      const status = this.getConnectionStatus(connectionId)
      
      if (!status.isConnected) {
        throw new Error('连接未建立')
      }
      
      if (!force && status.databases && status.databases.length > 0) {
        return status.databases
      }
      
      try {
        const databases = await DatabaseService.listDatabases(connectionId)
        this.setConnectionStatus(connectionId, {
          databases: databases || []
        })
        return databases
      } catch (error) {
        throw error
      }
    },
    
    // 设置默认连接
    async setDefaultConnection(connectionId) {
      try {
        await DatabaseService.setDefaultConfig(connectionId)
        
        // 更新本地状态
        this.connections.forEach(conn => {
          conn.isDefault = conn.id === connectionId
        })
        
      } catch (error) {
        this.errors.set(`setDefault:${connectionId}`, error.message)
        throw error
      }
    },
    
    // 获取默认连接
    async getDefaultConnection() {
      try {
        const defaultConfig = await DatabaseService.getDefaultConfig()
        return defaultConfig
      } catch (error) {
        console.warn('Failed to get default connection:', error)
        return null
      }
    },
    
    // 导入连接配置
    async importConnections(configs) {
      const results = {
        success: 0,
        failed: 0,
        errors: []
      }
      
      for (const config of configs) {
        try {
          await this.saveConnection(config)
          results.success++
        } catch (error) {
          results.failed++
          results.errors.push({
            config: config.name,
            error: error.message
          })
        }
      }
      
      return results
    },
    
    // 导出连接配置
    exportConnections(includePasswords = false) {
      return this.connections.map(conn => {
        const exported = { ...conn }
        
        // 可选择是否包含密码
        if (!includePasswords) {
          delete exported.password
        }
        
        return exported
      })
    },
    
    // 清除错误信息
    clearError(key) {
      if (key) {
        this.errors.delete(key)
      } else {
        this.errors.clear()
      }
    },
    
    // 获取错误信息
    getError(key) {
      return this.errors.get(key)
    },
    
    // 重置store
    reset() {
      this.connections = []
      this.connectionStatus.clear()
      this.activeConnectionId = null
      this.loading = false
      this.errors.clear()
    }
  }
}) 
 